/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package frm.billingAndPaymentProcessing.managedbean;

import commonInfrastructure.accountManagement.session.EmployeeSessionBean;
import frm.billingAndPaymentProcessing.entity.IncomingBillEntity;
import frm.billingAndPaymentProcessing.entity.VoucherEntity;
import frm.billingAndPaymentProcessing.session.VoucherSessionBean;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.faces.event.PhaseEvent;
import javax.servlet.http.HttpSession;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRExporter;
import net.sf.jasperreports.engine.JRExporterParameter;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import net.sf.jasperreports.engine.export.JRPdfExporter;
import org.primefaces.model.DefaultStreamedContent;
import org.primefaces.model.StreamedContent;

/**
 *
 * @author xhx
 */
@ManagedBean
@ViewScoped
public class ManageVoucherManagedBean {
private VoucherEntity voucher;
private String employee;

@EJB
VoucherSessionBean voucherSessionBean;
@EJB
EmployeeSessionBean employeeSessionBean;

private StreamedContent file;
private boolean view = false;

    /** Creates a new instance of ManageVoucherManagedBean */
    public ManageVoucherManagedBean() {
    }
    
    public void initView(PhaseEvent event){
        if(voucher ==null){
            voucher = (VoucherEntity)FacesContext.getCurrentInstance().getExternalContext().getFlash().get("voucher");
        }
        setEmployee(employeeSessionBean.getEmployeeById(getVoucher().getIssuedBy()).getName());
    }
    
    public void exportToPDFBySQLConn(ActionEvent event){
        try {
            
            List<IncomingBillEntity> voucherList = new ArrayList<IncomingBillEntity>();
            voucherList.add(voucher.getIncomingbill());
            
            JRBeanCollectionDataSource jrResultSetDataSource = new JRBeanCollectionDataSource(voucherList);
            
            HashMap parameters = new HashMap();
            parameters.put("IMAGEPATH", "http://localhost:8080/MerlionFoodERP-war/jasperreports/cherry.jpg");
            
            String path = FacesContext.getCurrentInstance().getExternalContext().getRealPath("jasperreports");
            String fileName = path+"/voucher.jasper";
            String outFileName = path+"/Voucher_"+voucher.getId()+".pdf";
            // Fill the report using an empty data source
            JasperPrint print = JasperFillManager.fillReport(fileName, parameters, jrResultSetDataSource);
            
            // Create a PDF exporter
            JRExporter exporter = new JRPdfExporter();
            
            // Configure the exporter (set output file name and print object)
            exporter.setParameter(JRExporterParameter.OUTPUT_FILE_NAME, outFileName);
            exporter.setParameter(JRExporterParameter.JASPER_PRINT, print);
            
            // Export the PDF file
            exporter.exportReport();
            setView(true);
            
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Report generated successfully.", ""));
        }
        catch (JRException jrex){
            System.out.println("********** Jasperreport Exception");
            jrex.printStackTrace();
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "There is something wrong...", ""));
        }
        catch (Exception ex){
            ex.printStackTrace();
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "There is something wrong...", ""));
        }
    }
    
    public StreamedContent getFile() throws IOException {
        String viewName = "/jasperreports/Voucher_"+voucher.getId()+".pdf";
        InputStream stream = ((HttpSession)FacesContext.getCurrentInstance().getExternalContext().getSession(true)).getServletContext().getResourceAsStream(viewName);
        
        if (stream == null){
            System.out.println("************Cannot find file.");
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "The report has not been generated yet", ""));
        }
        setFile(new DefaultStreamedContent(stream, "application/pdf","downloadFile.pdf"));
        return this.file;
    }
     
    public VoucherEntity getVoucher() {
        return voucher;
    }

    public void setVoucher(VoucherEntity voucher) {
        this.voucher = voucher;
    }

    public String getEmployee() {
        return employee;
    }

    public void setEmployee(String employee) {
        this.employee = employee;
    }

    /**
     * @param file the file to set
     */
    public void setFile(StreamedContent file) {
        this.file = file;
    }

    /**
     * @return the view
     */
    public boolean isView() {
        return view;
    }

    /**
     * @param view the view to set
     */
    public void setView(boolean view) {
        this.view = view;
    }
}
